<template>
  <el-row>
    <el-col :span="18" class="col-container">
      部门名称：<el-input v-model="deptName" placeholder="请输入部门名称" style="width: 200px;margin-right: 10px;" />
      负责人：<el-input v-model="manager" placeholder="请输入部门负责人" style="width: 200px;margin-right: 10px;" />
      <el-button type="primary" @click="selectInfosByWhere"><el-icon>
          <Search />
        </el-icon>查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </el-col>
    <el-col :span="6" class="col-container">
      <el-button type="primary" @click="openAddDialog"><el-icon>
          <Plus />
        </el-icon>添加部门</el-button>
    </el-col>
  </el-row>

  <el-table :data="deptList" stripe border style="margin-top: 20px">
    <el-table-column prop="name" label="部门名称" width="180" />
    <el-table-column prop="address" label="部门地址" width="200" />
    <el-table-column prop="phone" label="部门电话" width="180" />
    <el-table-column prop="manager" label="部门负责人" width="150" />
    <el-table-column prop="remark" label="备注" />
    <el-table-column label="操作" width="200">
      <template #default="{ row }">
        <el-button type="primary" size="small" @click="openEditDialog(row.id)">
          <el-icon>
            <Edit />
          </el-icon>编辑
        </el-button>

        <el-button type="danger" size="small" @click="handleDelete(row.id)">
          <el-icon>
            <Delete />
          </el-icon>删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加/修改部门对话框 -->
  <el-dialog v-model="dialogVisible" :title="isEditing ? '修改部门' : '新增部门'" width="600px">
    <el-form :model="form" label-width="120px" ref="formRef">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="部门地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入部门地址" />
      </el-form-item>
      <el-form-item label="部门电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入部门电话" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-input v-model="form.manager" placeholder="请输入部门负责人" />
      </el-form-item>
      <el-form-item label="上级部门" prop="parentDept">
        <el-select v-model="form.parentDept" placeholder="请选择上级部门" clearable>
          <el-option v-for="dept in deptOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">正常</el-radio>
          <el-radio :label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/request.js'

// 部门列表
const deptList = reactive([])

// 表单数据
const form = reactive({
  id: null,
  name: '',
  address: '',
  phone: '',
  manager: '',
  remark: '',
  status: 0,
  parentDept: null
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' }
  ],
  manager: [
    { required: true, message: '部门负责人不能为空', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
})

// 对话框相关
const dialogVisible = ref(false)
const formRef = ref(null)
const isEditing = ref(false)

// 部门选项（用于上级部门选择）
const deptOptions = ref([])

// 查询条件
const deptName = ref('')
const manager = ref('')

// 打开添加部门对话框
const openAddDialog = () => {
  isEditing.value = false
  Object.assign(form, {
    id: null,
    name: '',
    address: '',
    phone: '',
    manager: '',
    remark: '',
    status: 0,
    parentDept: null
  })
  dialogVisible.value = true
}

// 打开编辑部门对话框
const openEditDialog = (id) => {
  isEditing.value = true
  axios({
    url: '/dept/getDeptById.do',
    method: 'post',
    params: { id }
  }).then(res => {
    form.id = res.id
    form.name = res.name
    form.address = res.address
    form.phone = res.phone
    form.manager = res.manager
    form.remark = res.remark
    form.status = res.status
    form.parentDept = res.parentDept || null
    dialogVisible.value = true
  }).catch(error => {
    ElMessage.error('网络请求失败，请检查网络是否畅通!')
  })
}

// 提交表单
const submitForm = () => {
  if (!form.name || !form.manager || !form.phone) {
    ElMessage.error('请填写完整信息')
    return
  }

  if (isEditing.value) {
    // 修改部门
    axios({
      url: '/dept/updateDept.do',
      method: 'post',
      params: {
        id: form.id,
        name: form.name,
        address: form.address,
        phone: form.phone,
        manager: form.manager,
        remark: form.remark,
        status: form.status,
        parentDept: form.parentDept
      }
    }).then(res => {
      if (res.result === 'success') {
        ElMessage.success('修改成功!')
        dialogVisible.value = false
        loadDeptData()
      } else {
        ElMessage.error('修改失败，请检查数据是否正确!')
      }
    }).catch(error => {
      ElMessage.error('网络请求失败，请检查网络是否畅通!')
    })
  } else {
    // 添加部门
    axios({
      url: '/dept/addDept.do',
      method: 'post',
      params: {
        name: form.name,
        address: form.address,
        phone: form.phone,
        manager: form.manager,
        remark: form.remark,
        status: form.status,
        parentDept: form.parentDept
      }
    }).then(res => {
      if (res.result === 'success') {
        ElMessage.success('保存成功!')
        dialogVisible.value = false
        loadDeptData()
      } else {
        ElMessage.error('保存失败，请检查数据是否正确!')
      }
    }).catch(error => {
      ElMessage.error('网络请求失败，请检查网络是否畅通!')
    })
  }
}

// 删除部门
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '确定要删除该部门吗？此操作不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios({
      url: '/dept/deleteDept.do',
      method: 'post',
      params: { id }
    }).then(res => {
      if (res.result === 'success') {
        ElMessage.success('删除成功!')
        loadDeptData()
      } else {
        ElMessage.error('删除失败，请检查数据是否正确!')
      }
    }).catch(error => {
      ElMessage.error('网络请求失败，请检查网络是否畅通!')
    })
  }).catch(() => { })
}

// 加载部门数据
const loadDeptData = () => {
  axios({
    url: '/dept/getAllDepts.do',
    method: 'post'
  }).then(res => {
    deptList.splice(0, deptList.length, ...res)
  }).catch(error => {
    ElMessage.error('网络请求失败，请检查网络是否畅通!')
  })
}

// 条件查询
const selectInfosByWhere = () => {
  axios.post('/dept/searchDept.do', {
    name: deptName.value,
    manager: manager.value
  }).then(res => {
    if (res.data) {
      deptList.splice(0, deptList.length, ...res.data)
    } else {
      ElMessage.error('查询失败，返回数据格式不正确!')
    }
  }).catch(error => {
    ElMessage.error('查询失败，请检查网络是否畅通!')
  })
}

// 重置查询条件
const resetSearch = () => {
  deptName.value = ''
  manager.value = ''
  loadDeptData()
}

// 页面加载时初始化数据
onMounted(() => {
  loadDeptData()
})
</script>

<style>
.el-row {
  margin-top: 0rem;
  height: 60px;
  padding: 0cm;
  margin-bottom: 0;
}

.col-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 60px;
  padding: 0px;
}
</style>